package com.magicapi.config;

import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.extension.parsers.DynamicTableNameParser;
import com.baomidou.mybatisplus.extension.parsers.ITableNameHandler;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantSqlParser;
import com.google.common.collect.Maps;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.Map;
import java.util.Properties;

//import org.mybatis.spring.boot.autoconfigure.ConfigurationCustomizer;

@Configuration
//@MapperScan("com.zhirui.lmwy.wms.*.dao")
public class MyBatisConfig {

    public static ThreadLocal<String> newTableNames = new ThreadLocal<>();

    /**
     * 分页插件: 实现物理分页
     */
    @Bean
    public MyPaginationInterceptor paginationInterceptor() {
        MyPaginationInterceptor paginationInterceptor = new MyPaginationInterceptor();
        ArrayList<ISqlParser> iSqlParsers = new ArrayList<>();
        TenantSqlParser tenantSqlParser = new TenantSqlParser();
//        tenantSqlParser.setTenantHandler(new TenantHandler() {
//            @Override
//            public Expression getTenantId(boolean where) {
////                return new StringValue("b45551e5f8de4efc800e3677ef68cb39");
//                return new StringValue(tenantId);
//            }

//            @Override
//            public String getTenantIdColumn() {
//                //指定表中的租户列
//                return "tenant_id";
//            }

//            @Override
//            public boolean doTableFilter(String tableName) {
//                return false;
//            }
//        });
//        iSqlParsers.add(tenantSqlParser);

        // 动态改变表名，但是是固定一个表，例如"user",
        DynamicTableNameParser dynamicTableNameParser = new DynamicTableNameParser();
        Map<String, ITableNameHandler> tableNameHandlerMap = Maps.newHashMap();
        tableNameHandlerMap.put("user", new ITableNameHandler() {
            @Override
            public String dynamicTableName(MetaObject metaObject, String sql, String tableName) {
                return newTableNames.get();
            }
        });
        newTableNames.remove();
        dynamicTableNameParser.setTableNameHandlerMap(tableNameHandlerMap);
        iSqlParsers.add(dynamicTableNameParser);

        paginationInterceptor.setSqlParserList(iSqlParsers);
        return paginationInterceptor;
    }


    //    /**
//     * 打印 sql
//     */
//    @Bean
//    public PerformanceInterceptor performanceInterceptor() {
//        PerformanceInterceptor performanceInterceptor = new PerformanceInterceptor();
//        //格式化sql语句
//        Properties properties = new Properties();
//        properties.setProperty("format", "true");
//        performanceInterceptor.setProperties(properties);
//        return performanceInterceptor;
//    }
}
